//
//  GMGallery.m
//  gentleman
//
//  Created by 范月成 on 2017/12/6.
//  Copyright © 2017年 fancy. All rights reserved.
//

#import "GMGallery.h"
#import "VendorHeader.h"
#import "ClassesHeader.h"
#import "API.h"


@implementation GMGalleryComment
@end

@implementation GMGalleryInfo
@end

@implementation GMGalleryTag

- (instancetype)initWithName:(NSString *)name
                        tags:(NSArray *)tags {
    if (self = [super init]) {
        self.name = [name copy];
        self.tags = [tags copy];
    }
    return self;
}
@end

@implementation GMGallery

+ (void)getWithArtworkUrl:(NSString *)url
                completed:(getGalleryCompleted)completed {
    //?inline_set=ts_m 小图,40一页
    //?inline_set=ts_l 大图,20一页
    NSString *finalUrl = [NSString stringWithFormat:@"%@?inline_set=ts_l&nw=always", url];
    
    [XMCenter sendRequest:^(XMRequest * _Nonnull request) {
        request.url = finalUrl;
        request.httpMethod = kXMHTTPMethodGET;
        request.responseSerializerType = kXMResponseSerializerRAW;
    } onSuccess:^(id  _Nullable responseObject) {
        if ([[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] containsString:@"This gallery has been removed"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                !completed?:completed([NSError errorWithDomain:@"This gallery has been removed" code:444 userInfo:nil], nil);
            });
            return;
        }
        TFHpple *parser = [[TFHpple alloc] initWithHTMLData:responseObject];
        GMGallery *gallery = [[GMGallery alloc] initWithParser:parser];
        [gallery requestShowkey:completed];
    } onFailure:^(NSError * _Nullable error) {
        !completed?:completed(error, nil);
    }];
}

- (instancetype)initWithParser:(TFHpple *)parser {
    self = [super init];
    if (self) {
        //解析缩略图
        [self thumbnailWithParser:parser];
        //解析基础信息
        [self infoWithParser:parser];
        //解析评论
        [self commentsWithParser:parser];
        //解析tag
        [self tagWithParser:parser];
        //解析收藏状态
        [self statusWithParser:parser];
        //解析api
        [self apiWithParser:parser];
    }
    return self;
}

- (void)thumbnailWithParser:(TFHpple *)parser {
    TFHppleElement *element = [parser searchWithXPathQuery:kArtworkThumbnailQuery].firstObject;
    self.thumbnail = [element.raw subStringBetween:@"(" and:@")"];
    
    TFHppleElement *testImageElement = [parser searchWithXPathQuery:@"//div[@id='gdt']//a"].firstObject;
    self.testUrl = [testImageElement objectForKey:@"href"];
}

- (void)infoWithParser:(TFHpple *)parser {
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    NSArray *values = [parser searchWithXPathQuery:kArtworkInfoQuery];
    NSArray *keys = @[@"posted", @"parent", @"visible", @"language", @"size", @"length", @"favorited"];
    for (NSInteger i = 0; i<values.count; i++) {
        TFHppleElement *parentElment = values[i];
        TFHppleElement *subElment = [parentElment searchWithXPathQuery:@"//td [@class='gdt2']"].firstObject;
        info[keys[i]] = subElment.text;
    }
    
    self.info = [GMGalleryInfo yy_modelWithJSON:info];
}

- (void)commentsWithParser:(TFHpple *)parser {
    NSArray *comments = [parser searchWithXPathQuery:kArtworkCommentsQuery];
    if (comments.count) {
        TFHppleElement *hppleElement = [comments firstObject];
        NSArray *oneComments = [hppleElement searchWithXPathQuery:@"//div[@class='c1']"];
        NSMutableArray *commentsArr = [NSMutableArray array];
        for (TFHppleElement *element in oneComments) {
            GMGalleryComment *comment = [[GMGalleryComment alloc] init];
            //发布日期
            TFHppleElement *repostTime = [element searchWithXPathQuery:@"//div[@class='c3']"].firstObject;
            comment.repostTime = [self getDateWithLocalStyle:repostTime.text];
            //名字
            TFHppleElement *reporter = [element searchWithXPathQuery:@"//div[@class='c3']//a"].firstObject;
            comment.reporter = reporter.text;
            //评分
            TFHppleElement *score = [element searchWithXPathQuery:@"//div[@class='c5 nosel']//span"].firstObject;
            comment.score = score.text != nil ? [NSString stringWithFormat:@"Score %@",score.text] : @"Uploader";
            //评论内容
            TFHppleElement *contentElement = [element searchWithXPathQuery:@"//div[@class='c6']"].firstObject;
            comment.content = contentElement.raw;
            //TODO c8是修改日期,暂时没爬取
            [commentsArr addObject:comment];
        }
        self.comments = commentsArr;
    }
}

- (void)tagWithParser:(TFHpple *)parser {
    NSMutableArray *tagArr = [NSMutableArray array];
    NSArray *tagListArr = [parser searchWithXPathQuery:kArtworkTagsQuery];
    for (TFHppleElement *element in tagListArr) {
        GMGalleryTag *tag = [[GMGalleryTag alloc] init];
        TFHppleElement *leftElement = [element searchWithXPathQuery:@"//td[@class='tc']"].firstObject;
        tag.name = [leftElement.text stringByReplacingOccurrencesOfString:@":" withString:@""];
        NSArray *rightArr = [element searchWithXPathQuery:@"//td[2]//div//a"];
        NSMutableArray *tags = [NSMutableArray new];
        for (TFHppleElement *element in rightArr) {
            NSString *title = element.text;
            //如果标签有多个含义,则第一个为最原始的含义
            if ([title containsString:@"|"]) {
                title = [title componentsSeparatedByString:@" | "].firstObject;
            }
            NSDictionary *tagItem = @{@"title":title, @"url":[element objectForKey:@"href"]};
            [tags addObject:tagItem];
        }
        tag.tags = tags;
        [tagArr addObject:tag];
    }
    self.tagArr = tagArr;
}

- (void)statusWithParser:(TFHpple *)parser {
    TFHppleElement *element = [parser searchWithXPathQuery:@"//div[@id='gdf']//a"].firstObject;
    self.isFavorite = ![element.text containsString:@"Add to Favorites"];
}

- (void)apiWithParser:(TFHpple *)parser {
    NSArray *apiArr = [parser searchWithXPathQuery:@"//script[@type='text/javascript']"];
    if (apiArr.count<2) {
        return;
    }
    TFHppleElement *apiElement = apiArr[1];
    NSString *jsHtml = apiElement.firstChild.content;
    NSString *regexStr = @"var apiuid =.*?;";
    NSString *apiuid = [[self matchString:jsHtml toRegexString:regexStr].firstObject copy];
    apiuid = [apiuid stringByReplacingOccurrencesOfString:@"var apiuid = " withString:@""];
    apiuid = [apiuid stringByReplacingOccurrencesOfString:@";" withString:@""];
    self.apiuid = apiuid;
    
    NSString *regexStr1 = @"var apikey = \".*?\";";
    NSString *apikey = [[self matchString:jsHtml toRegexString:regexStr1].firstObject copy];
    apikey = [apikey stringByReplacingOccurrencesOfString:@"var apikey = \"" withString:@""];
    apikey = [apikey stringByReplacingOccurrencesOfString:@"\";" withString:@""];
    self.apikey = apikey;
}

- (void)requestShowkey:(getGalleryCompleted)completed {
    [XMCenter sendRequest:^(XMRequest * _Nonnull request) {
        request.httpMethod = kXMHTTPMethodGET;
        request.url = self.testUrl;
        request.responseSerializerType = kXMResponseSerializerRAW;
    } onSuccess:^(id  _Nullable responseObject) {
        NSString *html = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *regexStr = @"var showkey=\".*?\";";
        NSString *showkey = [[self matchString:html toRegexString:regexStr].firstObject copy];
        showkey = [showkey stringByReplacingOccurrencesOfString:@"var showkey=\"" withString:@""];
        showkey = [showkey stringByReplacingOccurrencesOfString:@"\";" withString:@""];
        self.showkey = showkey;
        !completed?:completed(nil, self);
    } onFailure:^(NSError * _Nullable error) {
        !completed?:completed(error, nil);
    }];
}

//根据正则表达式筛选
- (NSArray *)matchString:(NSString *)string toRegexString:(NSString *)regexStr {
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
    //match: 所有匹配到的字符,根据() 包含级
    NSMutableArray *array = [NSMutableArray array];
    for (NSTextCheckingResult *match in matches) {
        for (int i = 0; i < [match numberOfRanges]; i++) {
            //以正则中的(),划分成不同的匹配部分
            NSString *component = [string substringWithRange:[match rangeAtIndex:i]];
            [array addObject:component];
        }
    }
    return array;
}

//获取回复时间
- (NSString *)getDateWithLocalStyle:(NSString *)time {
    NSArray *array = [time componentsSeparatedByString:@" "];
    NSString *day = array[2];
    NSString *monthStr = array[3];
    NSInteger month = [self.engMonthArr indexOfObject:monthStr] + 1;
    NSString *year = [array[4] substringWithRange:NSMakeRange(0, 4)];
    NSString *hourAndMintime = array[5];
    
    NSString *utcTime = [NSString stringWithFormat:@"%4ld-%2ld-%2ld %@",(long)[year integerValue],(long)month,(long)[day integerValue],hourAndMintime];
    NSString *dateNowStr = [self changeTimeToLocalTime:utcTime];
    return dateNowStr;
}

- (NSArray *)engMonthArr {
    return @[@"January",@"February",@"March",@"April",@"May",@"June",@"July",@"August",@"September",@"October",@"November",@"December"];
}

//转换成当前时区的时间格式
- (NSString *)changeTimeToLocalTime:(NSString *)time {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *utcDate = [dateFormatter dateFromString:time];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSTimeInterval timeValue = [zone secondsFromGMTForDate:utcDate];
    NSDate *dateNow = [utcDate dateByAddingTimeInterval:timeValue];
    NSString *dateNowStr = [dateFormatter stringFromDate:dateNow];
    return dateNowStr;
}

@end
